#!/usr/bin/python
# -*- coding: utf-8 -*-
#初始化t_profile_item表数据
import MySQLdb
import json
import sys


conn = MySQLdb.connect(host="keepfitdb.mysql.rds.aliyuncs.com",user="for_ol",passwd="Abcd1234",db="coacht",port=3306)

def getUserActoins(page,size=1000):
    start = page * size;
    sql = "select * from t_user_action limit %d , %d " % (start,size)
    print sql
    cur = conn.cursor()
    cur.execute(sql)
    rs = cur.fetchall()
    cur.close()
    return rs

size = 1000
def updateUserAction(id,lvl,level_info):
    sql = "update t_user_action set lvl = %s,level_info = '%s' where id = %s" % (lvl,level_info,id)
    cur = conn.cursor()
    cur.execute(sql)
    cur.close()

if __name__ == "__main__":
    page = 0
    print "start..."
    while 1 :
        user_actions = getUserActoins(page,size)
        count_action = len(user_actions)
        print count_action
        for i in range(count_action):
            row = user_actions[i]
            jsonStr = row[4]
            if "" == jsonStr:
                continue
            obj = json.loads(jsonStr)
            level_info = {"action":obj['action'],"duration":obj['duration'],"rep":obj['rep']}
            if obj.has_key("level"):
                lvl = obj['level']
            else:
                lvl = 1
            id = row[0]
            level_info_str = json.dumps(level_info)
            updateUserAction(id,lvl,level_info_str)
        if count_action < size:
            break
        page +=1

    print "end"
